package bank

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
	"strings"
)

/*
*
 */
func adjustmentAdd(c *gin.Context) {
	sql.HttpHandle(sql.ADD, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		var bean model.BankAdjustment
		if err := c.Bind(&bean); err != nil {
			fmt.Println(err)
			db.Error = errors.New(sql.ErrorParams)
			return db, nil
		}

		tx := db.Begin()

		// 1、创建调账记录
		if err := tx.Create(&bean).Error; err != nil {
			tx.Callback()
			tx.Error = errors.New(sql.ErrorService)
			return tx, nil
		}

		// 2、修改收款账户金额
		if err := balanceChanges(tx, bean.CollectionAccountId, bean.Money, true); err != nil {
			return tx, nil
		}

		//3、修改付款账户金额
		if err := balanceChanges(tx, bean.PaymentAccountId, bean.Money, false); err != nil {
			return tx, nil
		}

		tx.Commit()
		return db, bean
	})
}

func adjustmentList(c *gin.Context) {
	sql.HttpHandle(sql.GET, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		index := c.Query("pageIndex")
		size := c.Query("pageSize")
		pageIndex, indexErr := strconv.Atoi(index)
		pageSize, sizeError := strconv.Atoi(size)
		if indexErr == nil && sizeError == nil {
			db = db.Offset((pageIndex - 1) * pageSize).Limit(pageSize)
		}
		var list []model.BankAdjustment
		tx := db.Begin()
		if err := tx.Find(&list).Error; err != nil {
			tx.Callback()
			return db, nil
		}
		var bankList []model.BankAccount
		if err := tx.Find(&bankList).Error; err != nil {
			tx.Callback()
			return db, nil
		}
		tx.Commit()
		for i, adjustment := range list {
			for _, account := range bankList {
				str := strings.Replace(account.CardNumber, " ", "", -1)
				if len(str) > 4 {
					a := []rune(str)
					str = string(a[len(a)-4:])
				}
				if account.ID == uint(adjustment.PaymentAccountId) {
					adjustment.PaymentAccount = account.Bank + str
				}
				if account.ID == uint(adjustment.CollectionAccountId) {
					adjustment.CollectionAccount = account.Bank + str
				}
			}
			list[i] = adjustment
		}
		return db, list
	})

}

func adjustmentDelete(c *gin.Context) {
	sql.HttpHandle(sql.ADD, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		idStr := c.Query("id")
		var bean model.BankAdjustment
		tx := db.Begin()

		// 1、查询要删除的账单
		if err := tx.Where("id = ?", idStr).Find(&bean).Error; err != nil {
			tx.Callback()
			tx.Error = errors.New(sql.ErrorService)
			return tx, nil
		}

		// 2、修改收款账户金额
		if err := balanceChanges(tx, bean.CollectionAccountId, bean.Money, false); err != nil {
			return tx, nil
		}

		//3、修改付款账户金额
		if err := balanceChanges(tx, bean.PaymentAccountId, bean.Money, true); err != nil {
			return tx, nil
		}

		//4、删除数据
		if err := tx.Delete(&bean).Error; err != nil {
			tx.Callback()
			tx.Error = errors.New(sql.ErrorService)
			return tx, nil
		}

		tx.Commit()
		return db, bean
	})
}
